package com.ruoyi.common.utils;

import cn.hutool.core.util.IdUtil;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.ruoyi.common.config.OssConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

@Component
public class AliyunOssUtils {
    private static Logger logger = LoggerFactory.getLogger(AliyunOssUtils.class);

    public AjaxResult uploadFile(MultipartFile file) throws IOException {
        try {
            OSS ossClient = new OSSClientBuilder().build(OssConfig.END_POINT, OssConfig.ACCESS_KEY_ID, OssConfig.ACCESS_KEY_SECRET);
            String directory = OssConfig.FILENAME_PREFIX + StringUtils.replace(DateUtils.getDate(),"-","") + "/";
            if (!ossClient.doesObjectExist(OssConfig.BUCKET_NAME,directory)) {
                // 创建目录
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(0);
                PutObjectRequest request = new PutObjectRequest(OssConfig.BUCKET_NAME, directory, new ByteArrayInputStream(new byte[0]), metadata);
                ossClient.putObject(request);
            }
            String filename = directory + IdUtil.fastSimpleUUID() + getExtentionName(file.getOriginalFilename());
            ossClient.putObject(OssConfig.BUCKET_NAME, filename, file.getInputStream());
            ossClient.shutdown();
            logger.debug("oss文件已推送 {}", filename);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", OssConfig.CDN);
            ajax.put("fileName", "/" + filename);
            ajax.put("newFileName", FileUtils.getName(filename));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            logger.error("上传OSS出错", e);
            throw e;
        }
    }

    public AjaxResult uploadFile(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            OSS ossClient = new OSSClientBuilder().build(OssConfig.END_POINT, OssConfig.ACCESS_KEY_ID, OssConfig.ACCESS_KEY_SECRET);
            String directory = OssConfig.FILENAME_PREFIX + StringUtils.replace(DateUtils.getDate(),"-","") + "/";
            if (!ossClient.doesObjectExist(OssConfig.BUCKET_NAME,directory)) {
                // 创建目录
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentLength(0);
                PutObjectRequest request = new PutObjectRequest(OssConfig.BUCKET_NAME, directory, new ByteArrayInputStream(new byte[0]), metadata);
                ossClient.putObject(request);
            }
            String filename = directory + IdUtil.fastSimpleUUID() + getExtentionName(file.getName());
            ossClient.putObject(OssConfig.BUCKET_NAME, filename, fis);
            ossClient.shutdown();
            logger.debug("oss文件已推送 {}", filename);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", OssConfig.CDN);
            ajax.put("fileName", "/" + filename);
            ajax.put("newFileName", FileUtils.getName(filename));
            ajax.put("originalFilename", file.getName());
            return ajax;
        } catch (Exception e) {
            logger.error("上传OSS出错", e);
            throw e;
        }
    }

    public void downloadFile(String objectName, HttpServletResponse response) throws Exception {
        try {
            OSS ossClient = new OSSClientBuilder().build(OssConfig.END_POINT, OssConfig.ACCESS_KEY_ID, OssConfig.ACCESS_KEY_SECRET);
            OSSObject ossObject = ossClient.getObject(OssConfig.BUCKET_NAME, objectName);
            ossClient.shutdown();
            // 设置响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectName, "UTF-8"));

            // 将文件写入响应
            try (InputStream inputStream = ossObject.getObjectContent(); OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[1024];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }

            logger.debug("文件已从OSS下载 {}", objectName);
        } catch (Exception e) {
            logger.error("从OSS下载文件出错", e);
            throw e;
        }
    }

    private String getExtentionName(String filename) {
        if (StringUtils.isBlank(filename)) {
            return "";
        }
        int index = filename.lastIndexOf(".");
        if (index == -1) {
            return "";
        }
        return filename.substring(index);
    }
}
